//
//  ByUIMineDataVC.m
//  chequanbao_ios
//
//  Created by mc on 2017/5/15.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIMineDataVC.h"
#import "ByTextView.h"
// api
#import "ByApiUser.h"
@interface ByUIMineDataVC ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate>
// view
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *iconView;
@property (nonatomic, strong) UILabel     *sexLabel;
@property (nonatomic, strong) ByTextView  *infoView;
@property (nonatomic, strong) UITextField *nickNameTF;

// data
@property (nonatomic, strong) NSArray *titlesAry;
@property (nonatomic, strong) NSMutableArray *placeAry;

// other
@property (nonatomic, strong) ByIconChooseDataSource *iconChooseDataSource;

@end

@implementation ByUIMineDataVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人资料";
    [self addLeftBackBarButtonItem];
    [self initTableView];
}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    self.tableView.top = self.view.safeAreaInsets.top;
    self.tableView.height = self.view.height - self.view.safeAreaInsets.top - self.view.safeAreaInsets.bottom;
}

#pragma mark -- 数据


#pragma mark -- getter
-(NSArray *)titlesAry{
    if (!_titlesAry) {
        _titlesAry = @[@"昵称",@"性别",@"简介"];
    }
    return _titlesAry;
}

-(NSMutableArray *)placeAry{
    if (!_placeAry) {
        NSString *sex;
        if (BY_USER.sex.intValue == 0) {
            sex = @"未设置";
        }else{
           sex = BY_USER.sex.intValue == 2?@"男":@"女";
        }
        _placeAry = [@[@"输入昵称",sex,@"介绍一下自己吧"] mutableCopy];
    }
    return _placeAry;
}

- (UIImageView *)iconView {
    if (!_iconView) {
        CGFloat width = [@"更换头像" getSizeOfString:14].width;
        _iconView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - width - 20)/2, 20, width + 20, width + 20)];
        _iconView.image = DEFAULT_HEAD;
        _iconView.layer.cornerRadius = _iconView.height / 2;
        _iconView.layer.masksToBounds = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickIcon)];
        _iconView.userInteractionEnabled = YES;
        [_iconView addGestureRecognizer:tap];
        
//        if (BY_USER.head.length != 0) {
            [_iconView setImageWithURL:[NSURL URLWithString:BY_USER.head] placeholderImage:DEFAULT_IMAGE completed:nil];
//        }
        
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, width + 20 - 25, width + 20, 25)];
        bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.35];
        [_iconView addSubview:bgView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, width, 20)];
        label.text = @"更换头像";
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = FONT(12);
        label.adjustsFontSizeToFitWidth = YES;
        [bgView addSubview:label];
    }
    return _iconView;
}

- (ByIconChooseDataSource *)iconChooseDataSource {
    if (!_iconChooseDataSource) {
        _iconChooseDataSource = [[ByIconChooseDataSource alloc] init];
        [_iconChooseDataSource fireWithViewController:self];
        _iconChooseDataSource.isEdit = YES;
    }
    return _iconChooseDataSource;
}


#pragma mark -- 创建视图
- (void)initTableView{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 110)];
    headerView.backgroundColor = [UIColor clearColor];
    [headerView addSubview:self.iconView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.estimatedRowHeight = 0;
    _tableView.estimatedSectionHeaderHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    _tableView.tableHeaderView = headerView;
    
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60 + 20)];
    UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10 + 20, SCREEN_WIDTH - 20, 50)];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    saveBtn.backgroundColor = BY_THEME_COLOR;
    saveBtn.layer.cornerRadius = 4.0;
    [footerView addSubview:saveBtn];
    [saveBtn addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    _tableView.tableFooterView = footerView;
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titlesAry.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *indentier = @"dataCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentier];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    for (UIView *subview in cell.subviews) {
        [subview removeFromSuperview];
    }
    // 背景视图
    CGFloat x,y,width,height;
    x = 10;
    y = 0;
    width = SCREEN_WIDTH - 2*x;
    height = 50;
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    bgView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.25];
    bgView.layer.cornerRadius = 4.0;
    [cell addSubview:bgView];
    
    // 标题
    x = 10;
    y = 10;
    width = [@"昵称" getSizeOfString:14].width;
    height = 30;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    titleLabel.font = FONT(14);
    titleLabel.textColor = [UIColor colorWithWhite:0.90 alpha:1];
    titleLabel.text = self.titlesAry[indexPath.section];
    [bgView addSubview:titleLabel];
    
    x = titleLabel.right + 30;
    y = 10;
    width = bgView.width - x;
    height = 30;
    
    ByModelUser *user = [ByCacheUser getUserInfo];
    // 昵称
    if (indexPath.section == 0) {
        _nickNameTF = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
        _nickNameTF.font = FONT(14);
        NSDictionary *attrDic = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
        _nickNameTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeAry[indexPath.section] attributes:attrDic];
        _nickNameTF.textColor = [UIColor whiteColor];
        if (user.nickname.length != 0) {
            _nickNameTF.text = user.nickname;
        }
        [bgView addSubview:_nickNameTF];
    }
    // 性别
    else if(indexPath.section == 1){
        _sexLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width - 40, height)];
        _sexLabel.font = FONT(14);
        _sexLabel.text = self.placeAry[indexPath.section];
        _sexLabel.textColor = [UIColor whiteColor];
        _sexLabel.tag = 11;
        [bgView addSubview:_sexLabel];
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(_sexLabel.right, 15, 20, 20)];
        img.image = [UIImage imageNamed:@"mine_arrow"];
        [bgView addSubview:img];
        
        
    }
    // 简介
    else if (indexPath.section == 2){
        _infoView = [[ByTextView alloc] initWithFrame:CGRectMake(x, 10, width, 30)];
        _infoView.placeholder = self.placeAry[indexPath.section];
        _infoView.placeholderTextColor = [UIColor whiteColor];
        _infoView.textColor = [UIColor whiteColor];
        _infoView.font = FONT(14);
        _infoView.backgroundColor = [UIColor clearColor];
        _infoView.tag = 12;
        [bgView addSubview:_infoView];
        if (user.sign.length != 0) {
            _infoView.text = user.sign;
        }
    
    }
    
    return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    // 性别
    if (indexPath.section == 1) {
        // 适配版本iOS8.0以上
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
            // 创建ActionSheet
            NSString *albumButtonTitle = @"男";
            NSString *cameraButtonTitle = @"女";
            NSString *cancelButtonTitle = @"取消";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            // 添加点击动作
            // 取消
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:nil];
            
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
            // 男
            UIAlertAction *albumAction = [UIAlertAction actionWithTitle:albumButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
                [self.placeAry replaceObjectAtIndex:1 withObject:@"男"];
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                
                }];
            // 女
            UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:cameraButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
                [self.placeAry replaceObjectAtIndex:1 withObject:@"女"];
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            }];
            
            // Add the actions.
            [alertController addAction:cancelAction];
            [alertController addAction:albumAction];
            [alertController addAction:cameraAction];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }
        // 适配版本8.0以下
        else {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
            sheet.tag = 301;
            [sheet showInView:self.view];
        }

    }
}

#pragma mark -- 相关事件
// 保存
- (void)saveAction:(UIButton *)button{
    ByModelUser *user = [ByCacheUser getUserInfo];
    NSString *sex;
    if (user.sex.intValue == 0) {
        sex = @"未设置";
    }else{
        sex = user.sex.intValue == 2?@"男":@"女";
    }
    if ([_nickNameTF.text isEqualToString:user.nickname] && [_sexLabel.text isEqualToString:sex] && [_infoView.text isEqualToString:user.sign]) {
        [ByCoreToolAlert showOnlyText:@"您没有修改信息"];
        return;
    }
    
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    if (_nickNameTF.text.length != 0) {
        model.nickname = _nickNameTF.text;
    }
    if (_sexLabel.text.length != 0) {
        if ([_sexLabel.text isEqualToString:@"未设置"]) {
            model.sex = @"0";
        }else{
            model.sex = [_sexLabel.text isEqualToString:@"男"]?@"2":@"1";
        }
    }
    if (_infoView.text.length != 0) {
        model.sign = _infoView.text;
    }
    model.uid = user.uid;
    [ByCoreToolAlert showLoadind:@"修改中..."];
    [ByApiUser updateUserInfo:model success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showOnlyText:result.data];
        user.nickname = _nickNameTF.text;
        if ([_sexLabel.text isEqualToString:@"未设置"]) {
            user.sex = @"0";
        }else{
            user.sex = [_sexLabel.text isEqualToString:@"男"]?@"2":@"1";
        }
        user.sign = _infoView.text;
        [ByCacheUser setUserInfo:user];
        [self dismissViewControllerAnimated:YES completion:nil];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
}

// 上传头像
- (void)clickIcon{
    [self.iconChooseDataSource makeConfigToSelectIcon];
    __weak typeof(self) weakself = self;
    [self.iconChooseDataSource setCompleteBlock:^(UIImage *image) {
        
        [weakself uploadIcon:image];
    }];
    
}

- (void)uploadIcon:(UIImage *)img{
   [self performSelector:@selector(afterLoad) withObject:nil afterDelay:0.01];
   [ByApiUser iconUpload:img success:^(ByNetBaseResult *result) {
       self.iconView.image = img;
       ByModelUser *user = BY_USER;
       user.head = BOYE_IMAGE_URL_ORIGINAL(result.data[@"id"]);
       [ByCacheUser setUserInfo:user];
       [ByCoreToolAlert showSuccessWithText:@"上传成功"];
  } failure:^(ByNetBaseResult *result) {
      [ByCoreToolAlert showFailureWithText:result.msg];
  }];
}

- (void)afterLoad{
    [ByCoreToolAlert showLoadind:@"上传中..."];
}

@end
